<?php
	session_start();
	require_once('../inc/fnc.php');
	/* require_once('../inc/conn.php');
	require_once('../inc/constants.php'); */
	
	// Initializing variables
	$email = mysql_prep(strtolower(trim($_POST['email'])));
	$name = mysql_prep(strtolower(trim($_POST['name'])));
	$pwd = mysql_prep($_POST['pwd']);

	$error['pwd'] = ($pwd == '' || $pwd == NULL || $pwd == "Password") ? $error['pwd']= 'null' : $error['pwd']= 'clear';
	
	//Check if the user is providing a valid invite key
	if(authenticateInvite($email,$pwd)){
	
		if (!(preg_match('/^[a-z\d_]{5,20}$/i', $name))) { $error['name']= 'false'; } elseif (!checkavailable($name)) { $error['name']= 'exist'; } else { $error['name']= 'clear'; }
	
		if (!check_email_address($email)) {
			$error['reg']= 'invalid';
		} else {
			$error['reg'] = (isEmailAvailable($email)) ? 'clear' : 'true';	//If true, email not available; if false, email is available
		} //if ($email == ''){
			
			
		if($error['reg'] == 'clear' && $error['pwd'] == 'clear' && $error['name'] == 'clear') {
		
			$t1=explode(' ',$name);
			$lname = array_pop($t1);
			$fname =implode(' ',$t1);
			
			$pwd = sha1($pwd);
			$time = time();
	
			$query = mysql_query("select max(userid) as uid from users");
			while($row = mysql_fetch_array($query)) {
				$userId = $row['uid'];
				$userId++;
			}
			
			if(isset($_POST['invitee'])){
				// If the user is registering from invite, set email verifation field to 'Y'
				$query = "INSERT INTO `users` (`userid`,`username`, `pwd`, `email`,`profile image path`, `time`, `isadmin`,`delete flag`,`email varification`) 
							VALUES ('{$userId}','{$name}', '{$pwd}', '{$email}', 'users/defaultAvatar/', '{$time}', 'N','N','Y')";
			} else {
				// Inserting basic user data into 'users' database table 
				$query = "INSERT INTO `users` (`userid`,`username`, `pwd`, `email`,`profile image path`, `time`, `isadmin`,`delete flag`,`email varification`) 
							VALUES ('{$userId}','{$name}', '{$pwd}', '{$email}', 'users/defaultAvatar/', '{$time}', 'N','N','N')";
			}
			
			$result = mysql_query( $query, $connection);
			if(!$result) {
				die("Failed To Register User: " . mysql_error());
			}
			
			// Generating activation link
			$rand = genRandomString(10);
			//$actLnk = DOMAIN . "?id=" . $userId . "&key=" . $rand . "&email=" . $email;
			
			$actLnk = DOMAIN . "/activate/" . $userId . "/" . $rand; // . "/" . $email;
			
			// Storing activation info in db
			$query = "INSERT INTO `activate` (`rand`, `email`, `flag`) 
						VALUES ('{$rand}', '{$email}', '0')";
						  
			$result = mysql_query( $query, $connection);
			if(!$result) {
				die("Inserting Activation link info Failed: " . mysql_error());
			}
			
			//Create User specific directory
			$currentTime = time('now');
			if(!is_dir('../users/'.date('my',$currentTime))) {
				mkdir('../users/'.date('MY',$currentTime), 0777);
				chmod('../users/'.date('MY',$currentTime), 0777);
			}
			
			//Create User specific directory
			$user_dir = '../users/'.date('MY',$currentTime).'/'.$userId;
			if(!is_dir($user_dir)){
				mkdir($user_dir, 0777);
				chmod($user_dir, 0777);
			}
			
			if(isset($_POST['invitee'])){
				$_SESSION['userId'] = $userId;
				unset($_SESSION['invite']);
				unset($_SESSION['ivtEmail']);
				$error['success'] = 'true';
			} else {
				// Sending Activation link to user
				
				$subject = 'Activation link to your story account';								// subject
				
				$message = $emailTop; 															// message
				$message .=	"<p>You've successfully created your Next Twist account.</p>
							<p>Click on the link below to activate your account</p><br/>
							<a href='" . $actLnk . "'>Activate now</a>";
				$message .=	 $emailBottom;

				$error['success'] = (sendMail($email, $subject, $message)) ? 'true' : 'false';		// Mail it
			}		
		}
		$error['invite'] = 'true';
	} else {
		$error['invite'] = 'false';
	}//if(authenticateInvite($email,$pwd)){ ENDS
	
	
	echo json_encode($error);
	
?>